<template>
  <view style="padding: 20rpx">
    <view class="option-list">
      <view
        class="option-item"
        :class="{ 'option-item-active': currentView === 'approved' }"
        @tap="changeView('approved')"
      >
        已报名
      </view>
      <view
        class="option-item"
        :class="{ 'option-item-active': currentView === 'pending' }"
        @tap="changeView('pending')"
      >
        待审
      </view>
      <view
        class="option-item"
        :class="{ 'option-item-active': currentView === 'rejected' }"
        @tap="changeView('rejected')"
      >
        拒绝
      </view>
    </view>
    <view
      class="player-item"
      v-for="(player, index) in filteredList"
      :key="index"
    >
      <image :src="getOneFromCover(player.cover)" class="player-img" />
      <view class="player-info">
        <view class="player-header">
          <view class="player-name">
            {{ player.tittle }}
          </view>
          <view class="player-name" v-if="player.state === 'approved'">
            {{ player.num }}票
          </view>
        </view>
        <text class="player-desc">{{ player.intro }}</text>
        <text class="player-reason" v-if="player.state === 'rejected'">
          拒绝理由：{{ player.cause }}
        </text>
        <view class="player-btn-container">
          <button
            class="player-btn"
            type="default"
            size="mini"
            @tap="goToActivity(player.actId)"
          >
            详情
          </button>
          <button
            class="player-btn"
            type="primary"
            size="mini"
            v-if="player.state !== 'approved'"
            @tap="playerEdit(player)"
          >
            {{ player.state === PublishState.pending ? "编辑" : "重报" }}
          </button>
          <button
            class="player-btn"
            type="warn"
            size="mini"
            v-if="player.state !== 'approved'"
            @tap="playerDelete(player)"
          >
            删除
          </button>
        </view>
      </view>
    </view>
    <view>
      <!-- 普通弹窗 -->
      <uni-popup ref="playerPopup" background-color="#fff" type="bottom">
        <view class="player-container">
          <uni-forms ref="playerRef" :model="playerForm" :rules="playerRules">
            <uni-forms-item name="images">
              <uni-file-picker
                limit="1"
                title="最多选择1张图片"
                fileMediatype="image"
                @select="playerImageSelect"
                @delete="playerImagesDelete"
                v-model="playerForm.images"
                return-type="array"
              ></uni-file-picker>
            </uni-forms-item>
            <uni-forms-item label="选手名称:" name="tittle" label-width="85">
              <uni-easyinput
                type="text"
                v-model="playerForm.tittle"
                placeholder="请输入投票标题"
              ></uni-easyinput>
            </uni-forms-item>
            <uni-forms-item label="选手描述:" name="intro" label-width="85">
              <uni-easyinput
                type="textarea"
                v-model="playerForm.intro"
                placeholder="请输入选手描述"
              ></uni-easyinput>
            </uni-forms-item>
            <view class="form-btn-container">
              <button @click="playerSubmit" class="submit-btn">修改选手</button>
            </view>
          </uni-forms>
        </view>
      </uni-popup>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, reactive } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { getMyEnteredAPI } from "@/api/vote";
import { deletePlayerAPI, updatePlayerAPI } from "@/api/player";
import {
  myEntereType,
  PublishState,
  addPlayerType,
  imageType,
} from "@/types/vote";
import { handleCoverToImageList, getOneFromCover } from "@/utils/vote";
import { uploadFileAPI } from "@/api/file";

onLoad(async () => {
  await getPlayerList();
});

const changeView = (view: string) => {
  currentView.value = view;
};

//选手表单
const playerForm: addPlayerType = reactive({
  images: [],
  tittle: "",
  intro: "",
  cover: "",
  state: PublishState.pending,
  actId: "",
});

const playerPopup = ref<UniHelper.UniPopupInstance>();

const playerRules: UniHelper.UniFormsRules = {
  images: {
    rules: [{ required: true, errorMessage: "请上传选手图片" }],
  },
  tittle: {
    rules: [
      { required: true, errorMessage: "请输入选手名称" },
      { maxLength: 16, errorMessage: "选手名称不能超过16个字符" },
    ],
  },
  intro: {
    rules: [
      {
        required: true,
        errorMessage: "请输入选手描述",
      },
      { maxLength: 100, errorMessage: "选手描述不能超过100个字符" },
    ],
  },
};
const playerRef = ref<UniHelper.UniFormsInstance>();

const currentView = ref("approved");

const playerList = ref<myEntereType[]>([]);

const filteredList = computed(() => {
  if (currentView.value === "all") {
    return playerList.value;
  }
  return playerList.value.filter(
    (activity) => activity.state === currentView.value
  );
});

//查看活动
const goToActivity = (actId: string) => {
  uni.navigateTo({ url: `/pages/vote/index?id=${actId}` });
};

//编辑选手
const playerEdit = (item: myEntereType) => {
  playerForm.images = handleCoverToImageList(item.cover);
  playerForm.id = item.id;
  playerForm.tittle = item.tittle;
  playerForm.intro = item.intro;
  playerForm.cover = item.cover;
  playerForm.actId = item.actId;
  playerPopup.value?.open?.();
};

//删除选手
const playerDelete = (item: myEntereType) => {
  //是否投票某选手提示弹窗
  uni.showModal({
    title: "删除提示",
    content: `是否删除选手【${item.tittle}】？`,
    success: async function (res) {
      if (res.confirm) {
        await deletePlayerAPI(item.id);
        uni.showToast({
          title: "删除成功",
          icon: "success",
          duration: 1000,
        });
        getPlayerList();
      } else if (res.cancel) {
        console.log("用户点击取消");
      }
    },
  });
};

// 获取选手列表
const getPlayerList = async () => {
  const res = await getMyEnteredAPI();
  playerList.value = res.data;
};

//选手
const playerImageSelect: UniHelper.UniFilePickerOnSelect = (event: any) => {
  const imageDatas = event.tempFiles.map((item: any) => {
    return { url: item.url, name: item.name };
  });
  playerForm.images.push(...imageDatas);
};

const playerImagesDelete: UniHelper.UniFilePickerOnDelete = (event: any) => {
  playerForm.images.splice(event.index, 1);
};

const playerSubmit = async () => {
  await playerRef.value?.validate?.();
  if (playerForm.images[0].url !== playerForm.cover) {
    await playerUploadFile(playerForm.images);
  }
  await updatePlayerAPI(playerForm);
  uni.showToast({
    title: "修改选手成功",
    icon: "success",
    duration: 1000,
  });
  await getPlayerList();
  playerPopup.value?.close?.();
};

const playerUploadFile = async (imageList: imageType[]) => {
  const uploadPromises = imageList.map((item) => uploadFileAPI(item));
  try {
    const responses = await Promise.all(uploadPromises);
    const fileUrlList = responses.flatMap((res) => res.data.fileUrl);
    playerForm.cover = fileUrlList.join(","); // 使用 join 代替 toString
  } catch (error) {
    console.error("上传文件时发生错误：", error);
    // 处理错误的逻辑，比如显示提示信息等
  }
};
</script>
<style scoped lang="scss">
.player-item {
  display: flex;
  margin: 10rpx 0;
  padding: 20rpx;
  border-radius: 12rpx;
  background-color: #fff;
  box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
  border: 1px solid #ebeef5;
  .player-img {
    width: 200rpx;
    height: 200rpx;
  }
  .player-info {
    flex-grow: 1;
    margin-left: 20rpx;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .player-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .player-name {
        font-size: 28rpx;
        font-weight: bold;
        color: #333;
      }
    }
    .player-desc {
      font-size: 24rpx;
      color: #666;
    }
    .player-reason {
      font-size: 24rpx;
      color: #f50;
    }
    .player-btn-container {
      display: flex;
      justify-content: flex-end;
      .player-btn {
        margin: 0 10rpx;
      }
    }
  }
}

.option-list {
  display: flex;
  justify-content: space-around;
  margin-top: 20rpx;
  .option-item {
    width: 30%;
    height: 72rpx;
    line-height: 72rpx;
    text-align: center;
    font-size: 28rpx;
    color: #333;
    background-color: #fff;
    position: relative;
  }
  .option-item-active {
    font-weight: bold;

    &::after {
      content: "";
      position: absolute;
      left: 0;
      top: 100%; /* 设置为 100% 以显示在下方 */
      margin-left: calc(50% - 22rpx);
      width: 44rpx;
      height: 6rpx; /* 条的高度 */
      background-color: #00fffb; /* 绿色背景 */
      border-radius: 4rpx; /* 可选，给条添加圆角 */
    }
  }
}

.player-container {
  padding: 20px;
  .form-btn-container {
    display: flex;
    justify-content: space-between;

    .submit-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 500rpx;
      background-color: #2979ff;
      height: 80rpx;
      font-size: 28rpx;
      border-radius: 8rpx;
      color: #fff;
    }
  }
}
</style>
